package com.chenjiahao.kaiyanwan.ui.videodetail

import android.annotation.TargetApi
import android.content.res.Configuration
import android.os.Build
import android.transition.Transition
import android.view.View
import android.widget.ImageView
import androidx.core.view.ViewCompat
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DecodeFormat
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.chenjiahao.kaiyanwan.*
import com.chenjiahao.kaiyanwan.base.BaseActivity
import com.chenjiahao.kaiyanwan.logic.util.StatusBarUtil
import com.chenjiahao.kaiyanwan.logic.util.WatchHistoryUtils
import com.hazz.kotlinmvp.mvp.model.bean.HomeBean
import com.scwang.smart.refresh.header.ClassicsHeader
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.listener.LockClickListener
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer
import kotlinx.android.synthetic.main.activity_category_detail.*
import kotlinx.android.synthetic.main.activity_video_detail.*
import kotlinx.android.synthetic.main.activity_video_detail.mRecyclerView
import kotlinx.android.synthetic.main.activity_video_detail.mRefreshLayout
import java.text.SimpleDateFormat
import java.util.*


class VideoDetailActivity : BaseActivity() {

    private var orientationUtils: OrientationUtils? = null

    /**
     * Item 详细数据
     */
    private var isTransition: Boolean = false
    private var isPlay: Boolean = false
    private var isPause: Boolean = false
    private var gsyVideoOption: GSYVideoOptionBuilder? = null
    private var transition: Transition? = null
    private var mMaterialHeader: ClassicsHeader? = null
    private var imageView:ImageView?=null

    companion object {
        const val IMG_TRANSITION = "IMG_TRANSITION"
        const val TRANSITION = "TRANSITION"
    }

    private val viewModel by lazy {
        ViewModelProvider(this).get(VideoDetailViewModel::class.java)
    }
    private val mAdapter by lazy { VideoDetailAdapter(this, viewModel.mItemList) }
    private val mFormat by lazy { SimpleDateFormat("yyyyMMddHHmmss"); }

    override fun layoutId(): Int {
        return R.layout.activity_video_detail
    }

    override fun initData() {
        viewModel.mItemData = intent.getSerializableExtra(BUNDLE_VIDEO_DATA) as HomeBean.Issue.Item
        isTransition = intent.getBooleanExtra(TRANSITION, false)
        saveWatchVideoHistoryInfo(viewModel.mItemData)
    }

    override fun initView() {
        //状态栏透明和间距处理
        StatusBarUtil.immersive(this)
        StatusBarUtil.setPaddingSmart(this, mVideoView)

        mRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
        mRecyclerView.adapter = mAdapter

        /***  下拉刷新  ***/
        //内容跟随偏移
        mRefreshLayout.setEnableHeaderTranslationContent(true)
        mMaterialHeader = mRefreshLayout.refreshHeader as ClassicsHeader?
        //设置下拉刷新主题颜色
        mRefreshLayout.setPrimaryColorsId(R.color.color_light_black, R.color.color_title_bg)
        mRefreshLayout.setOnRefreshListener {
            viewModel.loadVideoInfo(viewModel.mItemData)
            setVideo(viewModel.playUrl)
            setBackGroundAndRelatedData()
        }
        //设置相关视频 Item 的点击事件
        mAdapter.setOnItemDetailClick {
            viewModel.loadVideoInfo(it)
            setVideo(viewModel.playUrl)
            setBackGroundAndRelatedData()
        }
    }

    override fun start() {
        initTransition()
        initVideoViewConfig()
        viewModel.RelatedData.observe(this, Observer {
            val relateData = it.getOrNull()
            if (relateData != null) {
                viewModel.mItemList = relateData.itemList
                mAdapter.addData(viewModel.mItemList)
            } else {
                it.exceptionOrNull()?.printStackTrace()
            }
            dismissLoading();
        })
    }

    /**
     * 保存观看记录
     */
    private fun saveWatchVideoHistoryInfo(watchItem: HomeBean.Issue.Item) {
        //保存之前要先查询sp中是否有该value的记录，有则删除.这样保证搜索历史记录不会有重复条目
        val historyMap = WatchHistoryUtils.getAll(
            FILE_WATCH_HISTORY_NAME,
            KaiYanApplication.context
        ) as Map<*, *>
        for ((key, _) in historyMap) {
            if (watchItem == WatchHistoryUtils.getObject(
                    FILE_WATCH_HISTORY_NAME,
                    KaiYanApplication.context,
                    key as String
                )
            ) {
                WatchHistoryUtils.remove(FILE_WATCH_HISTORY_NAME, KaiYanApplication.context, key)
            }
        }
        WatchHistoryUtils.putObject(
            FILE_WATCH_HISTORY_NAME, KaiYanApplication.context, watchItem, "" + mFormat.format(
                Date()
            )
        )
    }

    private fun initTransition() {
        if (isTransition && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            postponeEnterTransition()
            ViewCompat.setTransitionName(mVideoView, IMG_TRANSITION)
            addTransitionListener()
            startPostponedEnterTransition()
        } else {
            viewModel.loadVideoInfo(viewModel.mItemData)
            setVideo(viewModel.playUrl)
            setBackGroundAndRelatedData()
        }
    }


    /**
     * 初始化 VideoView 的配置
     */
    private fun initVideoViewConfig() {
        //设置旋转
        orientationUtils = OrientationUtils(this, mVideoView)
        //是否旋转
        mVideoView.isRotateViewAuto = false
        //是否可以滑动调整
        mVideoView.setIsTouchWiget(true)
        mVideoView.fullscreenButton.setOnClickListener {
            //直接横屏
            orientationUtils?.resolveByClick();
            //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
            mVideoView.startWindowFullscreen(this, true, true);
        }
        //增加封面
        imageView = ImageView(this)
        imageView?.scaleType = ImageView.ScaleType.CENTER_CROP
        Glide.with(this)
            .load(viewModel.mItemData.data?.cover?.feed)
            .centerCrop()
            .into(imageView!!)
        mVideoView.thumbImageView = imageView
        gsyVideoOption = GSYVideoOptionBuilder()
        gsyVideoOption?.setThumbImageView(imageView)
            ?.setVideoAllCallBack(object : GSYSampleCallBack() {
                override fun onPrepared(url: String?, vararg objects: Any?) {
                    super.onPrepared(url, *objects)
                    orientationUtils?.isEnable = true
                    isPlay = true
                }

                override fun onAutoComplete(url: String?, vararg objects: Any?) {
                    super.onAutoComplete(url, *objects)
                }

                override fun onPlayError(url: String?, vararg objects: Any?) {
                    super.onPlayError(url, *objects)
                    showToast("播放失败")
                }

                override fun onQuitFullscreen(url: String?, vararg objects: Any?) {
                    super.onQuitFullscreen(url, *objects)
                    orientationUtils?.backToProtVideo()
                }
            }
            )?.build(mVideoView)
        //设置返回按键功能
        mVideoView.backButton.setOnClickListener({ onBackPressed() })
        //设置全屏按键功能
        mVideoView.fullscreenButton.setOnClickListener {
            //直接横屏
            orientationUtils?.resolveByClick()
            //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
            mVideoView.startWindowFullscreen(this, true, true)
        }
        //锁屏事件
        mVideoView.setLockClickListener(object : LockClickListener {
            override fun onClick(view: View?, lock: Boolean) {
                //配合下方的onConfigurationChanged
                orientationUtils?.isEnable = !lock
            }

        })
    }

    //设置播放url
    fun setVideo(url: String) {
        mVideoView.setUp(url, false, "")
        Glide.with(this)
            .load(viewModel.mItemData.data?.cover?.feed)
            .centerCrop()
            .into(imageView!!)
        mAdapter.addData(viewModel.mItemData)
        //开始自动播放
        mVideoView.startPlayLogic()
    }

    /**
     *   设置其他视频信息以及背景
     **/
    fun setBackGroundAndRelatedData() {
        //获取背景
        val backgroundUrl =
            viewModel.mItemData.data?.cover?.blurred
        //设置背景
        backgroundUrl.let {
            Glide.with(this)
                .load(it)
                .centerCrop()
                .format(DecodeFormat.PREFER_ARGB_8888)
                .transition(DrawableTransitionOptions().crossFade())
                .into(mVideoBackground)
        }
        //请求相关视频
        viewModel.requestRelatedData()
    }

    /**
     * 隐藏 Loading
     */
    fun dismissLoading() {
        mRefreshLayout.finishRefresh()
    }

    override fun onResume() {
        super.onResume()
        isPause = false
    }

    override fun onPause() {
        super.onPause()
        isPause = true
    }

    override fun onDestroy() {
        super.onDestroy()
        if (isPlay) {
            getCurPlay()?.release()
        }
        orientationUtils?.releaseListener()
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        if (isPlay && !isPause) {
            mVideoView.onConfigurationChanged(this, newConfig, orientationUtils, true, true);
        }
    }

    override fun onBackPressed() {
        if (orientationUtils != null) {
            orientationUtils!!.backToProtVideo()
        }
        if (GSYVideoManager.backFromWindowFull(this)) {
            return
        }
        super.onBackPressed()
    }


    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private fun addTransitionListener() {
        transition = window.sharedElementEnterTransition
        transition?.addListener(object : Transition.TransitionListener {
            override fun onTransitionResume(p0: Transition?) {
            }

            override fun onTransitionPause(p0: Transition?) {
            }

            override fun onTransitionCancel(p0: Transition?) {
            }

            override fun onTransitionStart(p0: Transition?) {
            }

            override fun onTransitionEnd(p0: Transition?) {
                viewModel.loadVideoInfo(viewModel.mItemData)
                setVideo(viewModel.playUrl)
                val backgroundUrl =
                    viewModel.mItemData.data?.cover?.blurred
                //设置背景
                backgroundUrl.let {
                    Glide.with(this@VideoDetailActivity)
                        .load(it)
                        .centerCrop()
                        .format(DecodeFormat.PREFER_ARGB_8888)
                        .transition(DrawableTransitionOptions().crossFade())
                        .into(mVideoBackground)
                }
                viewModel.requestRelatedData()
                p0?.removeListener(this)
            }

        })
    }

    private fun getCurPlay(): GSYVideoPlayer? {
        return if (mVideoView.getFullWindowPlayer() != null) {
            mVideoView.getFullWindowPlayer()
        } else mVideoView
    }


}
